/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import database.DBCachedConnection;
import database.DBCachedConnection;
import database.DBProperties;
import database.DBProperties;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 *
 * @author Tobias
 */
public final class DataBase implements DBProperties {
    
    private String DB_url = "";
    private String DB_username = "";
    private String DB_password = "";
    private String DB_driver = "";
    private Connection con = null;
    private static DataBase theInstance = null;
    private final String property_filename = System.getProperty("user.dir") + File.separator + "src" + File.separator + "database" + File.separator + "db_props.properties";
    private DBCachedConnection cc;
    
    private DataBase() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
        loadProperties();
        Class.forName(DB_driver);
        connect();
    }
    
    public static DataBase getInstance() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
        if (theInstance == null) {
            theInstance = new DataBase();
            System.out.println(theInstance);
        }
        return theInstance;
    }
    
    public void connect() throws SQLException {
        con = DriverManager.getConnection(DB_url, DB_username, DB_password);
        cc = new DBCachedConnection(con);
    }
    
    private void loadProperties() throws FileNotFoundException, IOException {
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(property_filename);
        props.load(fis);
        
        this.DB_url = props.getProperty("DB_url");
        this.DB_username = props.getProperty("DB_username");
        this.DB_password = props.getProperty("DB_password");
        this.DB_driver = props.getProperty("DB_driver");
        
        //System.out.println(DB_url + " " + DB_username + " " + DB_password + " " + DB_password);
    }
    
    public Statement getStatement() throws Exception {
        if (cc != null && con != null) {
            return cc.getStatement();
        }
        throw new Exception("not connected to DB schooldb");
    }
    
    public void releaseStatement(Statement stat) throws Exception {
        if (cc != null && con != null) {
            cc.releaseStatement(stat);
            return;
        }
        throw new Exception("not connected to DB schooldb");
    }

    public Connection getCon() {
        return con;
    }
}

